﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Meqs.Entity;
using System.Web.Services;
using Meqs.Logic;
using Meqs.Logic.Interface;


public partial class Credit_Teacher_Reprots_StuExamReport : ScoreInputBasePage
{
    /// <summary>
    /// 显示录入
    /// </summary>
   // protected string title = "初一一班 语文 期末成绩录入";
    /// <summary>
    /// 班级信息
    /// </summary>
    protected ClsInfo cls = null;
    /// <summary>
    /// 课程信息
    /// </summary>
    //protected GlobalCauseInfo cause = null;

    protected IList<GlobalCauseInfo> listCause = null;
    protected ClassResultExamList cresultList = null;
    /// <summary>
    /// 学生列表信息
    /// </summary>
    protected IList<StudentInfo> studentInfo = null;
    /// <summary>
    /// 成绩信息
    /// </summary>
    protected IList<StuExamDetail> stuExamDetail = null;

    /// <summary>
    /// 校考列表
    /// </summary>
    protected IList<ExamsSchool> examschool = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {   
            BindSchoolYear();
            selYear_TextChanged(selYear, new EventArgs());
            selClass_TextChanged(selClass, new EventArgs());
            Bind(); 
        }
    }

    private void Bind()
    { 
        int classid = 0;
        int schoolYear = 0, term = 0;  

        string[] outString = selYear.SelectedValue.Split(new char[] { ',' });
        if (outString.Length != 2)
            return;

        if (!Int32.TryParse(outString[0], out schoolYear))
            return;

        if (!Int32.TryParse(outString[1], out term))
            return;

        if (!Int32.TryParse(selClass.SelectedValue, out classid))
            return; 

        if (classid == null || classid <= 0)
            return;
        cls = Container<IClsInfoLogic>.Instance.FindById(classid); 
        listCause = GetCauseByCls(cls.RID); 

        #region 过滤科目权限
        Dictionary<int, List<int>> dicMpc = new Dictionary<int, List<int>>();//保存了班级和科目的id
        if (!SchoolCommon.CheckRole((int)RoleKeyEnum.School_Header, schoolYear, term))
        { 
            bool canUseManage = SchoolCommon.CheckRole((int) RoleKeyEnum.Class_Header, schoolYear, term);
            if (canUseManage) //若是班主任
            {
                List<int> allCauseID = new List<int>();
                foreach (GlobalCauseInfo g in listCause)
                {
                    allCauseID.Add(g.RID);
                }

                IList<ClsInfo> listClsTemp = Container<IClsInfoLogic>.Instance.SelectHisClsInfoByHeader(schoolYear,
                                                                                                        Common.
                                                                                                            GetUserInfo()
                                                                                                            .UID);
                foreach (ClsInfo item in listClsTemp)
                {  
                    if (!dicMpc.ContainsKey(item.RID))
                        dicMpc.Add(item.RID, allCauseID);
                } 
            }

            canUseManage = SchoolCommon.CheckRole((int) RoleKeyEnum.Class_Teacher, schoolYear, term);
            if (canUseManage)
            {
                //若是任课老师
                IList<TeachClsCause> listTcc =
                    Container<ITeachClsCauseLogic>.Instance.SelectHisTech(Common.GetUserInfo().UID, schoolYear);
                foreach (TeachClsCause item2 in listTcc)
                { 
                    List<int> tempG = new List<int>();

                    tempG.Add(item2.CauseID);
                    if (!dicMpc.ContainsKey(item2.ClsID))
                        dicMpc.Add(item2.ClsID, tempG);
                }
            }

            //过滤科目
            List<int> causeIds = new List<int>();
            foreach (KeyValuePair<int, List<int>> item3 in dicMpc)
            {
                if (item3.Key == cls.RID)
                {
                    causeIds.AddRange(item3.Value);
                }
            }

            if (causeIds.Count > 0)
            {
                for (int j = listCause.Count; j > 0; j--)
                {
                    if (!causeIds.Contains(listCause[j - 1].RID))
                        listCause.Remove(listCause[j - 1]);
                }
            }
            else
            {
                canUseManage = SchoolCommon.CheckRole((int)RoleKeyEnum.Teach_Director, schoolYear, term);
                if (!canUseManage)
                    listCause = new List<GlobalCauseInfo>();
            }
        }

        #endregion

        if (cls != null && listCause != null)
        {  
            Hashtable table = new Hashtable();
            table.Add("ClsID", classid);
            table.Add("IsEffect", 1);
            studentInfo = Container<Meqs.Logic.Interface.IStudentHistoryLogic>.Instance.FindHistoryStudents(schoolYear, term, classid, SchoolCommon.Sch_SchoolInfo.SchoolMark);

            table = new Hashtable();
            table.Add("ClassID", classid);
 //           table.Add("SubjectID", causeid);
            table.Add("SchoolYear", schoolYear);
            table.Add("SchoolTerm", term);
            table.Add("SchoolMark", SchoolCommon.Sch_SchoolInfo.SchoolMark);
            examschool = Container<IExamsSchoolLogic>.Instance.FindAll(table);

            table = new Hashtable();
            table.Add("SchoolMark", CommonScore.GetSchoolMark);
            table.Add("ClassID", classid);
         //   table.Add("CauseID", causeid);
            table.Add("SchoolYear", schoolYear);
            table.Add("Term",term);
            IList<ClassResultExamList> clist = Container<Meqs.Logic.Interface.IClassResultExamListLogic>.Instance.FindAll(table);
            if (clist.Count > 0)
            {
                string sids = "0";
                foreach (ClassResultExamList cl in clist)
                {
                    sids += "," + cl.RID;
                }
                cresultList = clist[0];
                table = new Hashtable();
                table.Add("SchoolMark", CommonScore.GetSchoolMark);
                table.Add("ClassID", classid);
              //  table.Add("CauseID", causeid);
                table.Add("TypeIDS", sids);
                stuExamDetail = Container<Meqs.Logic.Interface.IStuExamDetailLogic>.Instance.FindAll(table);
            }
            else
            {
                stuExamDetail = new List<StuExamDetail>(); 
            }
            Repeater1.DataSource = studentInfo;
            Repeater1.DataBind();
        }


    } 

    private List<int> GetUersRoleSubject(int schoolYear,int term,int userId)
    {
        Hashtable ht = new Hashtable();
        ht.Add("SchoolYear",schoolYear);
        ht.Add("Term",term);
        ht.Add("TeacherID", userId);

        IList<TeacherRoles> listRoles =  Container<ITeacherRolesLogic>.Instance.FindAll(ht);

      
        List<int> list = null;
        foreach (TeacherRoles item in listRoles)
        {
            if (item.RoleID == 1 || item.RoleID == 9)//校长
                return null;

            if(item.RoleID == 10)//班主任
            {
                int n =
                (int) SecurityTable.Security.Credit_CanView;
                list = SchoolCommon.CanViewSubjects(10, schoolYear, term);
            }
        }
        return list;
    }

 


    private IList<GlobalCauseInfo> GetCauseByCls(int clsId)
    {
        IList<GlobalCauseInfo> listInfo = null;
        listInfo = Container<ICouseGradeInfoLogic>.Instance.GetCauseByExamClass(clsId);

        return listInfo;
    }

    protected string GetHeader()
    {
        string header = "<th width='80px' style='text-align:left;padding-left: 5px;'>学号</th><th width='80px' style='text-align:left;padding-left: 5px;'>姓名</th>";

        if (listCause == null)
        {
            int clsId = 0;
            if (!Int32.TryParse(selClass.SelectedValue, out clsId))
                return "";
            listCause = GetCauseByCls(clsId);
        }
        foreach (GlobalCauseInfo item in listCause)
        { 
            header += "<th width='" + 90 + "px' style='text-align:right;padding-right: 5px;'>" + item.CauseName + "</th>";
        }

        return header;
    }


    /// <summary>
    /// 够找一个学生的考试成绩
    /// </summary>
    /// <param name="stuid"></param>
    /// <returns></returns>
    protected string GetStudent(int stuid, string StudentCode, string StudentName)
    {
        string header = "<tr  style='background-color: White;' id=" + stuid + " StudentCode=" + StudentCode + " StudentName= " + StudentName + " {scoreObj}>";
        string scoreObj = " stuid=" + stuid + " ";
        header += "<td width='80px' style='text-align:left;padding-left: 5px;'>" + StudentCode + "</td><td width='80px' style='text-align:left;padding-left: 5px;'>" + StudentName + "</td>";

        foreach (GlobalCauseInfo cause in listCause)
        { 
              header += "<td width='" + 90 + "px' style='text-align:right;padding-left: 5px;padding-right: 5px;'>";
              string score = GetKaoShiScore(stuid, cause.RID);
          //    scoreObj += " subject" + cause.RID + "=" + score + " ";
              if (!score.Equals("null"))
                  header += score;
              header += "</td>";

        }
       
        

        header += "</tr>";
      //  header = header.Replace("{scoreObj}", scoreObj);
        return header;
    }
    /// <summary>
    /// 获得某学生的统考分数
    /// </summary>
    /// <param name="stuId"></param>
    /// <returns></returns>
    private string GetKaoShiScore(int stuId,int causeId)
    {

        foreach (StuExamDetail g in stuExamDetail)
        {
            if (g.StudentID == stuId && g.CauseID == causeId)
            {
                return (g.Score == null) ? "null" : g.Score.ToString();
            }
        }
        return "null";
    }
    private string GetNextId(int subjid, int stuid, string stuCode)
    {
        for (int index = 0; index < studentInfo.Count; index++)
        {
            if (stuid == studentInfo[index].RID && index < studentInfo.Count - 1)
            {
                return "subject" + subjid + "_" + studentInfo[index + 1].StudentCode;
            }
        }
        return "";
    }
    protected void btnBind_Click(object sender, EventArgs e)
    {
        Bind();
        //  int classid = Convert.ToInt32(Request.QueryString["classid"]);
        //  int causeid = Convert.ToInt32(Request.QueryString["causeid"]);
        //  cls = Container<IClsInfoLogic>.Instance.FindById(classid);
        // // cause = Container<IGlobalCauseInfoLogic>.Instance.FindById(causeid);
        //  //if (cls != null)
        //  //{
        //  //    title = cls.ClsName + "  " + cause.CauseName + "  期末成绩录入";
        //  //}
        ////  cause = Container<IGlobalCauseInfoLogic>.Instance.FindById(causeid);
        //  Hashtable table = new Hashtable();
        //  table.Add("SchoolMark", CommonScore.GetSchoolMark);
        //  table.Add("ClassID", classid);
        //  table.Add("CauseID", causeid);
        //  table.Add("SchoolYear", SchoolCommon.Sch_SchoolInfo.SchoolYear);
        //  table.Add("Term", SchoolCommon.Sch_SchoolInfo.SchoolTerm);
        //  IList<ClassResultExamList> clist =
        //      Container<Meqs.Logic.Interface.IClassResultExamListLogic>.Instance.FindAll(table);
        //  table = new Hashtable();
        //  table.Add("ClsID", classid);
        //  table.Add("IsEffect", 1);
        //  studentInfo = Container<Meqs.Logic.Interface.IStudentInfoLogic>.Instance.FindAll(table);
        //  if (clist.Count > 0)
        //  {
        //      cresultList = clist[0];
        //      table = new Hashtable();
        //      table.Add("SchoolMark", CommonScore.GetSchoolMark);
        //      table.Add("ClassID", classid);
        //      table.Add("CauseID", causeid);
        //      table.Add("TypeID", clist[0].RID);
        //      stuExamDetail = Container<Meqs.Logic.Interface.IStuExamDetailLogic>.Instance.FindAll(table);

        //  }
        //  else
        //  {
        //      stuExamDetail = new List<StuExamDetail>();

        //  }
        //  Repeater1.DataSource = studentInfo;
        //  Repeater1.DataBind();
    }


    [WebMethod]
    public static ExamDetailSchool[] GetExamScores(int examtype, int examid, int[] subjectids, int classid)
    {
        if (examtype == 0)
        {
            Hashtable table = new Hashtable();
            table.Add("SchoolMark", CommonScore.GetSchoolMark);
            table.Add("ExamID", examid);
            table.Add("SubjectID", subjectids[0]);
            table.Add("ClsID", classid);
            IList<ExamDetailSchool> temp = Container<IExamDetailSchoolLogic>.Instance.FindAll(table);
            ExamDetailSchool[] edss = new ExamDetailSchool[temp.Count];
            for (int i = 0; i < temp.Count; i++)
            {
                edss[i] = temp[i];
            }
            return edss;
        }
        return new ExamDetailSchool[0];
    }



    /// <summary>
    /// 绑定班级下拉框
    /// </summary>
    protected void BindClass(int schoolYear, int term)
    {
        selClass.Items.Clear();
        IList<ClsInfo> schoolList = Container<IClassHistoryLogic>.Instance.FindClassesInSchoolYear(schoolYear, SchoolMark, null);
        ListSort<ClsInfo> sortList = new ListSort<ClsInfo>(schoolList, "Grade");
        schoolList = sortList.Sort();
        if (schoolList == null || schoolList.Count < 1)
            return;

        foreach (ClsInfo info in schoolList)
        {
            String str = "";
            switch (info.Grade)
            {
                case 1:
                    str = "一年级";
                    break;
                case 2:
                    str = "二年级";
                    break;
                case 3:
                    str = "三年级";
                    break;
                case 4:
                    str = "四年级";
                    break;
                case 5:
                    str = "五年级";
                    break;
                case 6:
                    str = "六年级";
                    break;
                case 7:
                    str = "初一";
                    break;
                case 8:
                    str = "初二";
                    break;
                case 9:
                    str = "初三";
                    break;
                case 10:
                    str = "高一";
                    break;
                case 11:
                    str = "高二";
                    break;
                case 12:
                    str = "高三";
                    break;
            }

            #region 班级过滤
            List<int> enableClassList = SchoolCommon.CanViewClasses((int)SecurityTable.Security.Credit_CanView, schoolYear, term);
            bool enableClass = false;
            if (!(enableClassList == null))
            {
                foreach (int i in enableClassList)
                {
                    if (info.RID == i)
                    {
                        enableClass = true;
                        break;
                    }
                }
                if (!enableClass)
                    continue;
            }
            #endregion

            selClass.Items.Add(new ListItem(String.Format("{0}({1})班", str, info.ClsNo), info.RID.ToString()));
        }
        selClass_TextChanged(selClass, new EventArgs());
    }


    /// <summary>
    /// 绑定学期下拉框
    /// </summary>
    protected void BindSchoolYear()
    {
        //Hashtable ht = new Hashtable();
        //ht.Add("SchoolMark", SchoolMark);
        //IList<StuCauseEvalHistory> historyList = Container<IStuCauseEvalHistoryLogic>.Instance.FindAll(ht);
        //if (historyList == null || historyList.Count < 1)
        //{
        //    selYear.Items.Add(new ListItem("没有历史数据", "-1"));
        //}
        //IList<String> strList = new List<String>();
        //if (historyList != null)
        //    foreach (StuCauseEvalHistory history in historyList)
        //    {
        //        String value = String.Format("{0},{1}", history.SchoolYear, history.Term);
        //        if (!strList.Contains(value))
        //        {
        //            int year = 0;
        //            int term = 0;
        //            if (!Int32.TryParse(history.SchoolYear.ToString(), out year))
        //                return;
        //            if (!Int32.TryParse(history.Term.ToString(), out term))
        //                return;
        //            String str = Common.ConvertYearAndTerm(year, term);
        //            selYear.Items.Add(new ListItem(str, value));
        //            strList.Add(value);
        //        }
        //    }

        SchoolInfo si = SchoolCommon.Sch_SchoolInfo;
        Hashtable ht = new Hashtable();
        ht.Add("SchoolMark", si.SchoolMark);
        IList<TermInfo> terms = Container<ITermInfoLogic>.Instance.FindAll(ht);
        foreach (TermInfo term in terms)
        {
            String str = Common.ConvertYearAndTerm(term.SchoolYear, term.Term);
            String value = String.Format("{0},{1}", term.SchoolYear, term.Term);
            selYear.Items.Add(new ListItem(str, value));
        }
    }

    /// <summary>
    /// 学期下拉框事件
    /// </summary>
    protected void selYear_TextChanged(object sender, EventArgs e)
    {
        int nYear = 0;
        int nTerm = 0;

        string[] outString = selYear.SelectedValue.Split(new char[] { ',' });
        if (outString.Length != 2)
            return;

        if (!Int32.TryParse(outString[0], out nYear))
            return;

        if (!Int32.TryParse(outString[1], out nTerm))
            return;

        BindClass(nYear, nTerm);
    }

    /// <summary>
    /// 学期下拉框事件
    /// </summary>
    protected void selClass_TextChanged(object sender, EventArgs e)
    {
        //int nYear = 0;
        //int nTerm = 0;
        //int nClass = 0;

        //string[] outString = selYear.SelectedValue.Split(new char[] { ',' });
        //if (outString.Length != 2)
        //    return;

        //if (!Int32.TryParse(outString[0], out nYear))
        //    return;

        //if (!Int32.TryParse(outString[1], out nTerm))
        //    return;

        //if (!Int32.TryParse(selClass.SelectedValue, out nClass))
        //    return;

        //Hashtable ht = new Hashtable();
        //ht.Add("RID", nClass);
        //ht.Add("SchoolMark", SchoolMark);
        //IList<ClsInfo> cilist = Container<IClsInfoLogic>.Instance.FindAll(ht);

        
    }

 
}
